package org.ysu.core;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.ysu.util.JwtUtil;
import org.ysu.util.YsuRequest;
import org.ysu.vo.ResultVO;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

//@Component
//@Order(1)
//@ConfigurationProperties(prefix = "filter.white")
@Setter
public class TokenFilter implements Filter {
    private List<String> urls;
    @Resource(name = "myredis")
    RedisTemplate<String,Object> redisTemplate;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //地址匹配工具
        AntPathMatcher pathMatcher=new AntPathMatcher();
        //获取token
        if(servletRequest instanceof HttpServletRequest){
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            String uri = request.getRequestURI();
            String token=request.getHeader("token");
            if("OPTIONS".equals(request.getMethod())){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
            for (String url:urls){
                if(pathMatcher.match(url,uri)){
                    filterChain.doFilter(servletRequest,servletResponse);
                    return;
                }
            }
            try {
                long id = JwtUtil.decode(token);
                String key = "admin::" + id + "::resource";
                if(!redisTemplate.hasKey(key)){
                    error(response,ResultVO.unlogin("登录超时"));
                }
                String resources = String.valueOf(redisTemplate.opsForValue().get(key));
                List<String> list = JSONObject.parseArray(resources, String.class);
                for (String url : list) {
                    if(pathMatcher.match(url,uri)){
                        YsuRequest ysuRequest = new YsuRequest(request);
                        ysuRequest.addParameter("openId",id);
                        filterChain.doFilter(ysuRequest,response);
                        return;
                    }
                }
                error(response,ResultVO.forbid());
            }catch (Exception ex){
                ex.printStackTrace();
                error(response,ResultVO.unlogin(ex.getMessage()));
            }
        }
    }

    public void error(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setHeader("Content-Type","application/json;charset=utf-8");
        ObjectMapper objectMapper=new ObjectMapper();
        response.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:8080");
        response.getWriter().write(objectMapper.writeValueAsString(resultVO));
    }
}
